import router from './router'
import NProgress from 'nprogress'
import { RouteLocationNormalized, NavigationGuardNext } from 'vue-router'
import Layout from '@/layout/index.vue'
import { getRoutes, getToken } from './utils/session'

const whiteList = ['/login']

const handleChild = (child: any) => {
  child.forEach(async (c: any) => {
    const component = c.component
    c.component = () => import(`@/views/${component}`)
  })
}

let routerCache: undefined

router.beforeEach((to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
  NProgress.start()

  if (getToken()) {
    if (!routerCache) {
      routerCache = getRoutes() // 缓存路由数据，避免页面在不刷新时，每次都执行路由添加的方法

      // 加载动态路由
      getRoutes().forEach((item: any) => {
        handleChild(item.children)

        router.addRoute({
          path: item.path,
          name: item.name,
          component: Layout,
          children: item.children
        })
      })

      next({ ...to, replace: true })
    } else {
      const routes = router.getRoutes().map(r => r.path)
      if (!routes.includes(to.path)) {
        next('/404')
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
